package com.huiminpay.merchant.service.impl;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.merchant.api.service.MerchantServiceApi;
import com.huiminpay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RestTemplate restTemplate;
    @Reference
    private MerchantServiceApi merchantService;
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    /**
     * 获取短信验证码
     * @param mobile
     * @return
     */
    @Override
    public String getSmsCode(String mobile)throws BusinessException{
        if (StringUtils.isEmpty(mobile)) {
//            throw new RuntimeException("手机号为空");
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        Boolean matches = PhoneUtil.isMatches(mobile);
        if (!matches){
            //手机号格式不正确
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        //判断手机号是否已注册
        merchantService.findMerchantByPhone(mobile);
        //声明body体
        Map body = new HashMap();
        body.put("mobile", mobile);

        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity httpEntity = new HttpEntity(body, headers);
        try {
            ResponseEntity<Map> exchange = restTemplate.exchange(smsUrl + "generate?name=sms&effectiveTime=" + effectiveTime,
                    HttpMethod.POST, httpEntity, Map.class);
            Map exchangeBody = exchange.getBody();
            Map result = (Map) exchangeBody.get("result");
            String key = result.get("key").toString();
            System.out.println(key);
            return key;
        } catch (Exception e) {
            log.error("发送验证码失败!");
            return null;
        }
    }

    /**
     * 校验验证码
     * @param verifiyKey
     * @param verifiyCode
     */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException{
        String url = smsUrl + "verify?name=sms&verificationCode=" + verifiyCode + "&verificationKey=" + verifiyKey;
        if (StringUtils.isEmpty(verifiyCode) || StringUtils.isEmpty(verifiyKey)) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }
        ResponseEntity<Map> entity = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
        Map body = entity.getBody();
        Boolean result = (Boolean) body.get("result");
        if (!result) {
            log.error("验证码错误! 验证码为{}", verifiyCode);
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }

}
